package com.wuyan.locationdog.ui.device


import android.graphics.Color
import android.os.Bundle
import android.util.Log
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.amap.api.location.AMapLocationListener
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.Marker
import com.amap.api.maps.model.MarkerOptions
import com.amap.api.maps.model.Polygon
import com.amap.api.maps.model.PolygonOptions
import com.amap.api.maps.model.Polyline
import com.amap.api.maps.model.PolylineOptions
import com.amap.api.services.core.PoiItemV2
import com.arcsoft.commonbase.base.BaseBindingActivity
import com.arcsoft.commonbase.bean.FenceBeanContent
import com.arcsoft.commonbase.bean.FenceSetTypeBean
import com.arcsoft.commonbase.ext.afterTextChange
import com.arcsoft.commonbase.ext.btnEnable
import com.arcsoft.commonbase.ext.customShowLong
import com.arcsoft.commonbase.ext.gone
import com.arcsoft.commonbase.ext.visible
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.SizeUtils
import com.blankj.utilcode.util.ToastUtils
import com.wuyan.locationdog.R
import com.wuyan.locationdog.adapter.FenceSetTypeAdapter
import com.wuyan.locationdog.databinding.FenceOvalActivityBinding
import com.wuyan.locationdog.help.DeviceHelp
import com.wuyan.locationdog.util.maputil.MapHelp
import com.wuyan.locationdog.util.maputil.MapLifecycle
import com.wuyan.locationdog.viewmodel.DeviceViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


class FenceOvalActivity : BaseBindingActivity<FenceOvalActivityBinding>() {
    private var polyline: Polyline? = null
    var isLocation: Boolean = true


    private var polygon: Polygon? = null

    private var mPoiItemV2: PoiItemV2? = null


    val mMarkList = mutableListOf<Marker>()
    val latLngs: MutableList<LatLng> = ArrayList()


    private val mViewModel: DeviceViewModel by viewModels()


    private val mAdapter by lazy { FenceSetTypeAdapter(R.layout.item_fence_alarm_set, null) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lifecycle.addObserver(MapLifecycle(binding.mapView, savedInstanceState))

    }


    override fun initData() {
        BarUtils.transparentStatusBar(this)
        val mFenceBeanContent = intent.getSerializableExtra("FenceBeanContent") as FenceBeanContent?

        binding.apply {
            if (isModify(mFenceBeanContent)) {
                binding.apply {
                    areaName.setText(mFenceBeanContent?.areaName)
                }
                val stringList = mFenceBeanContent?.coordinate?.split(";")
                stringList?.forEach {
                    if (!it.isNullOrEmpty()) {
                        val latLng = LatLng(it.split(",")[0].toDouble(), it.split(",")[1].toDouble())
                        val locationMarker = mapView.map.addMarker(
                            MarkerOptions()
                                .position(latLng)
                                .anchor(0.5f, 0.5f)
                                .icon(BitmapDescriptorFactory.fromResource(R.mipmap.mark_dot))
                        )
                        mMarkList.add(locationMarker)
                        latLngs.add(latLng)
                    }
                }
                drawLine()
                lifecycleScope.launch {
                    delay(500)
                    MapHelp.setMapBounds(mapView, latLngs)
                }

            } else {
                MapHelp.initLocation(mActivity, mLocationListener)
            }
            btnLast.gone()
            recyclerView.visible()

            btnEnable(btnSure, areaName)
            areaName.afterTextChange {
                btnEnable(btnSure, areaName)
            }
            // 设置点击地图事件监听器
            // 设置点击地图事件监听器
            mapView.map.setOnMapClickListener { latLng ->
                // 点击地图任意点时的响应事件
                Log.d("MapClick", "Clicked at: " + latLng.latitude + ", " + latLng.longitude)
                // 可以在这里添加点击地图任意点时的处理逻辑

                val locationMarker = mapView.map.addMarker(
                    MarkerOptions()
                        .position(latLng)
                        .anchor(0.5f, 0.5f)
                        .icon(BitmapDescriptorFactory.fromResource(R.mipmap.mark_dot))
                )
                mMarkList.add(locationMarker)
                latLngs.add(latLng)
                drawLine()
            }
            btnBack.setOnClickListener { finish() }
            btnClear.setOnClickListener {
                latLngs.clear()
                mMarkList.clear()
                mapView.map.clear(true)
                btnReturn.gone()
            }
            btnReturn.setOnClickListener {
                latLngs.removeLast()
                mMarkList.last().remove()
                mMarkList.removeLast()
                drawLine()
            }


            btnLast.gone()
            btnLast.setOnClickListener {
                btnSure.setText("下一步")

                recyclerView.gone()

                btnLast.gone()
            }
            btnSure.setOnClickListener {
                if (latLngs.size < 3) {
                    customShowLong("最少绘制三个点")
                    return@setOnClickListener
                }


                val map = HashMap<String, Any>()
//                map["deviceId"] = DeviceHelp.selectDeviceBeanContent.deviceId

                if (mAdapter.data.find { it.isSelect }?.name == "进入围栏区域报警") {
                    map["areaType"] = 1
                } else {
                    map["areaType"] = 2
                }
                map["areaName"] = binding.areaName.text.toString()
                var coordinate = ""
                latLngs.forEach {
                    coordinate += it.latitude.toString() + "," + it.longitude + ";"
                }
                map["coordinate"] = coordinate
                map["points"] = latLngs.size

                map["type"] = 2//类型1圆形2多边形3线路4行政区域

//                map["deviceIdList"] = arrayListOf("133", "134")

                if (isModify(mFenceBeanContent)) {
                    map["areaId"] = mFenceBeanContent!!.areaId
//                    mViewModel.updateArea(map)
                } else {
//                    mViewModel.addArea(map)
                }
                DeviceHelp.areaMap = map
                ActivityUtils.startActivity(MyDeviceSelectListActivity::class.java)

            }

            recyclerView.apply {
                layoutManager = GridLayoutManager(context, 2)
                adapter = mAdapter.apply {
                    val lists = mutableListOf<FenceSetTypeBean>()
                    //1禁止驶入区域2禁止驶出区域3区域限
                    if (mFenceBeanContent != null && mFenceBeanContent.areaType == 2) {
                        lists.add(FenceSetTypeBean(false, "进入围栏区域报警"))
                        lists.add(FenceSetTypeBean(true, "出围栏区域报警"))
                    } else {
                        lists.add(FenceSetTypeBean(true, "进入围栏区域报警"))
                        lists.add(FenceSetTypeBean(false, "出围栏区域报警"))
                    }

                    setNewInstance(lists)

                    addChildClickViewIds(R.id.shapeView)
                    setOnItemChildClickListener { adapter, view, position ->
                        data.find { it.isSelect }?.isSelect = false
                        data[position].isSelect = true
                        notifyDataSetChanged()
                    }
                }
            }



            btnLocation.setOnClickListener {

                if (isLocation) {
                    btnLocation.setImageResource(R.mipmap.map_location_device)
                    MapHelp.initLocation(mActivity, mLocationListener)
                } else {
                    btnLocation.setImageResource(R.mipmap.map_location_my)
//                    val latLng = LatLng(DeviceHelp.selectDeviceBeanContent.gaoDeLat, DeviceHelp.selectDeviceBeanContent.gaoDeLng)
//                    mapView.map?.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11F))
//                    MapHelp.setMapBounds(binding.mapView, mutableListOf(latLng))

                }

                isLocation = !isLocation

            }
        }

    }

    private fun isModify(mFenceBeanContent: FenceBeanContent?) = mFenceBeanContent != null

    override fun observe() {
        super.observe()
//        mViewModel.anyBean.observe(this) {
//            ActivityUtils.startActivity(DeviceFenceListActivity::class.java)
//            Bus.post(bus_fence_refresh, "")
//        }
//
//        Bus.observe<PoiItemV2>(BUS_FENCE_SEARCH, this) {
//            mPoiItemV2 = it
//
//
//        }


    }


    fun drawLine() {
        polygon?.remove()
        if (latLngs.isEmpty()) {
            binding.btnReturn.gone()
        } else {
            binding.btnReturn.visible()
        }
        if (latLngs.size == 2) {
            // 创建Polyline对象，并绘制线
            polyline = binding.mapView.map.addPolyline(
                PolylineOptions()
                    .addAll(latLngs) // 添加点
                    .width(SizeUtils.dp2px(3F).toFloat()) // 线宽
                    .color(Color.parseColor("#6E4DF3")) // 线颜色
            )
        } else {
            polyline?.remove()
            val polygonOptions = PolygonOptions()
                .addAll(latLngs) // latLngs是一个包含多边形所有顶点的List<LatLng>
                .fillColor(Color.parseColor("#336E4DF3"))
                .strokeColor(Color.parseColor("#6E4DF3"))
                .strokeWidth(SizeUtils.dp2px(3F).toFloat()) // 边界线宽度

            // 创建多边形填充区域
            polygon = binding.mapView.map.addPolygon(polygonOptions)
        }
    }


    //声明定位回调监听器
    private var mLocationListener = AMapLocationListener { amapLocation ->
        if (amapLocation != null) {
            if (amapLocation.errorCode == 0) {
                //实时位置上报
                Log.e("map", "定位成功:$amapLocation")
                val latLng = LatLng(amapLocation.latitude, amapLocation.longitude)
                binding?.mapView?.map?.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11F))


//                val latLng = LatLng(DeviceHelp.selectDeviceBeanContent.gaoDeLat, DeviceHelp.selectDeviceBeanContent.gaoDeLng)
//                binding.mapView.map?.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11F))

            } else {
                //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                Log.e(
                    "map", "location Error, ErrCode:" + amapLocation.errorCode + ", errInfo:" + amapLocation.errorInfo
                )
            }
        }
    }

}